package io.wit.modules.wit.service.impl;

import io.wit.modules.sys.dao.SysUserDao;
import io.wit.modules.sys.entity.SysUserEntity;
import io.wit.modules.sys.shiro.ShiroUtils;
import io.wit.modules.wit.dao.FarmDao;
import io.wit.modules.wit.entity.FarmEntity;
import io.wit.modules.wit.service.FarmService;
import io.wit.tool.ToolClient;
import io.wit.tool.ToolString;
import io.wit.tool.UploadFile;
import io.wit.tool.UploadObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("farmService")
public class FarmServiceImpl implements FarmService {

    @Autowired
	private FarmDao farmDao;

    @Autowired
    private SysUserDao sysUserDao;

    @Value("${upload_dir_window}")
    private String dir_window;

    @Value("${upload_dir_linux}")
    private String dir_linux;
	
	@Override
	public FarmEntity queryObject(Long farmId){
		return farmDao.queryObject(farmId);
	}

	@Override
	public String queryMap(final Long farmId){
        return ToolClient.queryJson(farmDao.queryMap(farmId));
	}
	
	@Override
	public List<FarmEntity> queryList(Map<String, Object> map){
		return farmDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return farmDao.queryTotal(map);
	}

    @Override
    public void save(final FarmEntity farm){
        farm.setCreateTime(new Date());
        farmDao.save(farm);
    }

	@Override
	public String save(final HttpServletRequest request){
        final String baseDir = ToolString.isLinuxOS() ? dir_linux : dir_window;
        final HashMap<String,String> formParams = ToolClient.getFormParams(request);
        final SysUserEntity user = ShiroUtils.getUserEntity();
        final HashMap<String,Object> subjects = sysUserDao.getSubjectInfo(user.getUsername());
        final UploadObject uploadObject = ToolClient.uploadFile(request,baseDir,"/images",3,true);
        final String errorMsg = uploadObject.getErrorMsg();
        if(errorMsg != null) return ToolClient.createJsonFail(errorMsg);
        final String validates = ToolClient.validateField(formParams,"name","type_id","province_id","city","county","address","area","species_id","link_man","link_tel");
        if(validates != null) return validates;
        formParams.put("subject_id",String.valueOf(subjects.get("data_id")));
        formParams.put("subject_name",String.valueOf(subjects.get("name")));
        final ArrayList<UploadFile> listFiles = uploadObject.getListFiles();
        final StringBuilder sb = new StringBuilder();
        for(int i = 0; i < listFiles.size(); i++){
            final String uri = listFiles.get(i).getUrlFile();
            if(sb.toString().length() > 0){
                sb.append(",").append(uri);
            }else{
                sb.append(uri);
            }
        }
        formParams.put("graphics",sb.toString());
        clearArea(formParams);
        final int rows = farmDao.saveFarmEntity(formParams);
        return ToolClient.executeRows(rows);
	}
	
	@Override
    public String update(final HttpServletRequest request){
        final String baseDir = ToolString.isLinuxOS() ? dir_linux : dir_window;
        final HashMap<String,String> formParams = ToolClient.getFormParams(request);
        final SysUserEntity user = ShiroUtils.getUserEntity();
        final HashMap<String,Object> subjects = sysUserDao.getSubjectInfo(user.getUsername());
        if(subjects == null || subjects.size() <= 0){
            return ToolClient.createJsonFail("该用户还没有经营主体!");
        }
        final UploadObject uploadObject = ToolClient.uploadFile(request,baseDir,"/images",3,false);
        final String errorMsg = uploadObject.getErrorMsg();
        if(errorMsg != null) return ToolClient.createJsonFail(errorMsg);
        final String validates = ToolClient.validateField(formParams,"data_id","name","type_id","address","area","species_id","link_man","link_tel");
        if(validates != null) return validates;
        formParams.put("subject_name",String.valueOf(subjects.get("name")));//主体登录账号不修改
        final ArrayList<UploadFile> listFiles = uploadObject.getListFiles();
        if(listFiles != null){
            final StringBuilder sb = new StringBuilder();
            for(int i = 0; i < listFiles.size(); i++){
                final String uri = listFiles.get(i).getUrlFile();
                if(sb.toString().length() > 0){
                    sb.append(",").append(uri);
                }else{
                    sb.append(uri);
                }
            }
            formParams.put("graphics",sb.toString());
        }
        clearArea(formParams);
        final int rows = farmDao.editFarmEntity(formParams);
        return ToolClient.executeRows(rows);
	}

    private void clearArea(final HashMap<String,String> formParams){
        final String province_id = formParams.get("province_id");
        if(province_id == null){
            formParams.remove("province_name");
        }
        final String city = formParams.get("city");
        if(city == null){
            formParams.remove("city_name");
        }
        final String county = formParams.get("county");
        if(county == null){
            formParams.remove("county_name");
        }
        final String villages = formParams.get("villages");
        if(villages == null){
            formParams.remove("villages_name");
        }
        final String hamlet = formParams.get("hamlet");
        if(hamlet == null){
            formParams.remove("hamlet_name");
        }
    }

	@Override
	public void update(FarmEntity farm){
		farmDao.update(farm);
	}
	
	@Override
	public void delete(Long farmId){
		farmDao.delete(farmId);
	}
	
	@Override
	public void deleteBatch(Long[] farmIds){
		farmDao.deleteBatch(farmIds);
	}

	@Override
	public List<FarmEntity> getAllFarm(Map<String, Object> map) {
		return farmDao.getAllFarm(map);
	}

	@Override
	public List<FarmEntity> farmList(Long subjectId) {
		return farmDao.farmList(subjectId);
	}

	@Override
	public List<FarmEntity> getFarm(Long county) {
		return farmDao.getFarm(county);
	}

	@Override
	public List<FarmEntity> farmLists(Long subjectId) {
		return farmDao.farmLists(subjectId);
	}

    @Override
    public String getTypeArea(){
        final List<Map<String,Object>> list = farmDao.getTypeArea();
        return ToolClient.queryJson(list);
    }

    @Override
    public String getTypeSales(){
        final List<Map<String,Object>> list = farmDao.getTypeSales();
        return ToolClient.queryJson(list);
    }

    @Override
    public String getTypePlant(){
        final List<Map<String,Object>> list = farmDao.getTypePlant();
        return ToolClient.queryJson(list);
    }

    @Override
    public String getTypeUnit(){
        final List<Map<String,Object>> list = farmDao.getTypeUnit();
        return ToolClient.queryJson(list);
    }

    @Override
    public List<Map<String,Object>> mapDashboard(final Map<String,Object> map){
        return farmDao.mapDashboard(map);
    }

    @Override
    public List<Map<String,Object>> getProxyArea(final Map<String,Object> map){
        return farmDao.getProxyArea(map);
    }
}
